package com.villaday.idf.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.custom.ConfirmDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.GetSecretKeyEntity;
import com.villaday.idf.model.PayEntity;
import com.villaday.idf.model.PayMent;
import com.villaday.idf.model.PayOrdersEntity;
import com.villaday.idf.model.vipOrder;
import com.villaday.idf.util.AliPayUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 充值
 * Created by Administrator on 2018/6/11 0011.
 */

public class UpgradeVipPaymentActivity extends BaseActivity implements OkHttpUtil.OnDataListener, BaseDialog.OnItemClickListener {

    @BindView(R.id.toolbar_text)
    Toolbar toolbar;

    private String userId;
    private LoadingDialog loadingDialog;
    private DecimalFormat decimal = new DecimalFormat("0.00");//保留两位小数使用
    private String rechargeMoney = "0";

    private boolean goPay = false;
    String rechargeInter = "微信";
    boolean isPay = false;
    String payNumber;
    Gson gson = new GsonBuilder().create();

    private GetSecretKeyEntity getSecretKeyEntity;
    private PayOrdersEntity ordersPrepare;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
/*            switch (msg.what) {
                case 1: {//SDK_PAY_FLAG
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    Log.e("logP", "resultStatus: " + resultStatus);
                    *//*Intent intent = new Intent(RechargeActivity.this, PayResultActivity.class);
                    intent.putExtra("type", 1);
                    intent.putExtra("payMode", "ali");
                    intent.putExtra("result", resultStatus);
                    startActivityForResult(intent, Constant.Code.PaymentCode);*//*
                    //paySucessLineAfter(getSecretKeyEntity.getData().getSerialNumber(), getSecretKeyEntity.getData().getOperateValue() + "", "8");
                    if ("200".equals(resultStatus)) {
                        resultPayDialog = ResultPayDialog.newInstance("恭喜您充值成功", 0);
                        resultPayDialog.show(getFragmentManager());
                        resultPayDialog.setOnItemClickListener(RechargeActivity.this);
                    } else {
                        resultPayDialog = ResultPayDialog.newInstance("充值失败", 1);
                        resultPayDialog.show(getFragmentManager());
                        resultPayDialog.setOnItemClickListener(RechargeActivity.this);
                    }

                    break;
                }
                default:

                    break;
            }*/
        }
    };

    @Override
    protected int getViewResId() {
        return R.layout.activity_upgrade_vip_payment;
    }

    @Override
    protected void init() {
        ToolBarUtil.init(toolbar, "升级成为VIP", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        userId = SharedPreferencesUtil.getUserId(this);

    }

    @Override
    protected void loadData() {
    }


    @OnClick(R.id.tv_payBtn)
    public void recharge(View view) {
        switch (view.getId()) {
            case R.id.tv_payBtn: {
                ConfirmDialog confirmDialog = ConfirmDialog.newInstance("确认升级VIP?", "取消", "确认");
                confirmDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v) {
                        if (v.getId() == R.id.btn_confirmDialog) {

                            loadingDialog = LoadingDialog.newInstance("支付中...");
                            loadingDialog.show(getFragmentManager(), "loading");
                            Map<String, Object> map = new HashMap<>();
                            OkHttpUtil.postJson(UpgradeVipPaymentActivity.this, Constant.URL.orders, new vipOrder(13), map, UpgradeVipPaymentActivity.this);

                        }
                    }
                });
                confirmDialog.show(getFragmentManager());

            }
            break;
        }

    }

    @Override
    public void onResponse(String url, String json) {

        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.orders.equals(url)) {
                LogeUtil.e("orders", json);
                ordersPrepare = gson.fromJson(json, PayOrdersEntity.class);
                if ("200".equals(ordersPrepare.getCode())) {
                    if (ordersPrepare.getBody() != null) {
                        requestPayment();
                    }
                } else {
                    ToastUtil.initToast(this, ordersPrepare.getMsg());
                }
            }
        }
/*
        if (!TextUtils.isEmpty(json)) {
            String decrypt = DesUtil.decrypt(json);
            if (Constant.URL.BalanceRecharge.equals(url)) {//充值
                dismissLoading();
                Log.e("loge", "BalanceRecharge 充值: " + decrypt);
                getSecretKeyEntity = gson.fromJson(decrypt, GetSecretKeyEntity.class);
                if (getSecretKeyEntity.getCode() == Constant.Integers.SUC) {
                    if (rechargeInter.equals("1")) {
                        goPay = true;
//                        Log.e("loge", "支付宝支付: " + decrypt);
//                        if (getSecretKeyEntity.getCode() == Constant.Integers.SUC) {
//                            Log.e("loge", "跳转支付: " + getSecretKeyEntity.getData().getPayData());
//                            Intent intent = new Intent();
////Intent intent = new Intent(Intent.ACTION_VIEW,uri);
//                            intent.setAction("android.intent.action.VIEW");
//                            Uri content_url = Uri.parse(getSecretKeyEntity.getData().getPayData());
//                            intent.setData(content_url);
//                            startActivity(intent);
//                        }
                    }
                } else {
                    dismissLoading();
                    ToastUtil.initToast(this, getSecretKeyEntity.getMessage());
                }
            } else if (Constant.URL.QueryOrder.equals(url)) {
                Log.e("loge", "查询订单是否支付成功: " + decrypt);
                dismissLoading();
                goPay = false;
                QueryOrderEntity wordEntity = gson.fromJson(decrypt, QueryOrderEntity.class);
                ToastUtil.initToast(this, wordEntity.getMessage());
                if (wordEntity.getCode() == Constant.Integers.SUC) {
                    *//**
         * 0000：交易成功
         3045：交易超时
         3008：余额不足
         3999：交易失败
         2008：交易处理中
         3050：交易已撤销
         *//*

                    String[] strings = wordEntity.getData().split("#");
                    switch (strings[0]) {
                        case "0000"://交易成功
                            showAppayRes("交易成功");
                            break;
                        case "3045"://交易超时
                            showAppayRes("交易超时");
                            break;
                        case "3008"://余额不足
                            showAppayRes("余额不足");
                            break;
                        case "3999"://交易失败
                            showAppayRes("交易失败");
                            break;
                        case "2008"://交易处理中
                            showAppayRes("交易处理中");
                            break;
                        case "3050"://交易已撤销
                            showAppayRes("交易已撤销");
                            break;
                    }
                }
            } else if (Constant.URL.UserOnlineRecharge.equals(url)) {
                Log.e("loge", "中卡充值: " + decrypt);
                dismissLoading();
                UserOnlineRechargeEntity uol = gson.fromJson(decrypt, UserOnlineRechargeEntity.class);
                if (uol.getCode() == Constant.Integers.SUC) {
                    dismissLoading();
                    SharedPreferencesUtil.saveWeChatPay(this, "weChatPay", "pay",
                            uol.getData().getOperateValue() + "", false);
                    String result = WeChatUtil.weChatPayRecharge(this, uol.getData());
                    if (TextUtils.isEmpty(result)) {
                        dismissLoading();
                    }
                    paySucessLineAfter(getSecretKeyEntity.getData().getSerialNumber(), "1500" + "", "3");


                } else {
                    ToastUtil.initToast(this, getSecretKeyEntity.getMessage());
                    ToastUtil.initToast(this, "暂不支付微信支付");
                }
            }
        }*/
    }

    public void showAppayRes(String res) {
        new AlertDialog.Builder(this)
                .setMessage(res)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        setResult(RESULT_OK);
                        finish();
                    }
                })
                .show();
    }

    public void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

   /* @Override
    protected void onResume() {
        super.onResume();
        if (isPay) {
            loadingDialog = LoadingDialog.newInstance("正在查询支付状态");
            loadingDialog.show(getFragmentManager(), "loading");
//            for (int i=0;i<4;i++){
            String jsonString = gson.toJson(new GetOrderStatus(payNumber, "0"));
            OkHttpUtil.postJson(Constant.URL.GetOrderStatus, DesUtil.encrypt(jsonString), new OkHttpUtil.OnDataListener() {
                @Override
                public void onResponse(String url, String json) {
                    try {
                        if (!TextUtils.isEmpty(json)) {
                            String decrypt = DesUtil.decrypt(json);
                            Log.e("loge", "订单状态: " + decrypt);
                            dismissLoading();
//                                {"ErrNum":"0","ErrMsg":"获取成功！","data":[{"status":"true"}]}
                            try {
                                String status = new JSONObject(decrypt).getJSONArray("data").getJSONObject(0).getString("status");
                                if (status.equals("true")) {
                                    ToastUtil.initToast(RechargeActivity.this, "订单支付成功");
                                    finish();
                                } else {
                                    ToastUtil.initToast(RechargeActivity.this, "订单支付失败");
                                }
                            } catch (Exception e) {
                                ToastUtil.initToast(RechargeActivity.this, "订单支付失败");
                            }

                        }
                    } catch (Exception e) {

                    }
                }

                @Override
                public void onFailure(String url, String error) {

                }
            });
//            }

        }
    }*/

    @Override
    public void onFailure(String url, String error) {
    }

    private void aliPay(GetSecretKeyEntity.DataEntity dataEntity) {
        dismissLoading();
        final String orderInfo = AliPayUtil.aliPay(this, dataEntity);
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
//                PayTask aliPay = new PayTask(RechargeActivity.this);
//                String result = aliPay.pay(orderInfo, true);

                Message msg = new Message();
                msg.what = 1;
//                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {
        }
    }


    /**
     * 直接跳支付接口
     */

    private void requestPayment() {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.pay, new PayMent(ordersPrepare.getBody().getOrderNo(), 2), objectObjectHashMap, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                dismissLoading();
                if (!TextUtils.isEmpty(json)) {
                    LogeUtil.e("pay11", json);
                    PayEntity payEntity = gson.fromJson(json, PayEntity.class);
                    if ("200".equals(payEntity.getCode())) {
                        SharedPreferencesUtil.saveWechatPayType(UpgradeVipPaymentActivity.this, "1");

                        SharedPreferencesUtil.saveWeOrderNum(UpgradeVipPaymentActivity.this, ordersPrepare.getBody().getOrderNo());
                        SharedPreferencesUtil.saveWechatPayType(UpgradeVipPaymentActivity.this,"1");
                        IWXAPI api = WXAPIFactory.createWXAPI(UpgradeVipPaymentActivity.this, Constant.ID.WeChat_APP_ID, true);
                        api.registerApp(Constant.ID.WeChat_APP_ID);
                        if (!api.isWXAppInstalled()) {//未安装微信
                            ToastUtil.initToast(UpgradeVipPaymentActivity.this, "您未安装微信");
                            return;
                        }
                        PayEntity.BodyEntity body = payEntity.getBody();
                        PayReq req = new PayReq();
                        //req.appId = "wxf8b4f85f3a794e77";  // ������appId
                        req.appId = body.getAppid();
                        req.partnerId = body.getPartnerid();
                        req.prepayId = body.getPrepayid();
                        req.nonceStr = body.getNoncestr();
                        req.timeStamp = body.getTimestamp();
                        req.packageValue = body.getPackageX();
                        req.sign = body.getSign();
                        req.extData = "app data";
                        api.sendReq(req);

                    } else {
                        ToastUtil.initToast(UpgradeVipPaymentActivity.this, payEntity.getMsg());
                    }


                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });


    }


    @Override
    protected void onRestart() {
        setResult(RESULT_OK);
        finish();
        super.onRestart();
    }
}
